
package x.trident.core.micro.gateway.modular.validate.impl;

import cn.hutool.core.util.StrUtil;
import x.trident.core.micro.gateway.modular.validate.BaseValidateService;
import x.trident.core.auth.api.SessionManagerApi;
import x.trident.core.auth.api.exception.AuthException;
import x.trident.core.auth.api.exception.enums.AuthExceptionEnum;
import x.trident.core.auth.api.pojo.login.LoginUser;
import x.trident.core.scanner.api.pojo.resource.ResourceDefinition;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Set;

/**
 * 资源权限校验
 *
 * @author Seven
 * @date 2018-08-13 21:52
 */
@Service
@Slf4j
public class PermissionValidateService extends BaseValidateService {

    @Resource
    private SessionManagerApi sessionManagerApi;

    @Override
    public void validate(String token, ResourceDefinition resourceDefinition) {

        // 如果需要鉴权
        if (resourceDefinition.getRequiredPermissionFlag()) {

            // token为空，返回用户校验失败
            if (StrUtil.isEmpty(token)) {
                throw new AuthException(AuthExceptionEnum.TOKEN_GET_ERROR);
            }

            // 获取token对应的用户信息
            LoginUser session = sessionManagerApi.getSession(token);
            if (session == null) {
                throw new AuthException(AuthExceptionEnum.AUTH_EXPIRED_ERROR);
            }

            // 验证用户有没有当前url的权限
            Set<String> resourceUrls = session.getResourceUrls();
            if (resourceUrls == null || resourceUrls.size() == 0) {
                throw new AuthException(AuthExceptionEnum.PERMISSION_RES_VALIDATE_ERROR);
            } else {
                if (!resourceUrls.contains(resourceDefinition.getUrl())) {
                    throw new AuthException(AuthExceptionEnum.PERMISSION_RES_VALIDATE_ERROR);
                }
            }
        }

    }

}
